import math

from moviepy.editor import VideoFileClip
from PIL import Image
import os
from scripts import str_parse
from scripts.beans import Storyboard

perImgDuration = 2  # 秒


# 视频文件路径
# 图片输出目录
def movie2Storyboard(video_path, srt_path, output_folder):
    clip = None
    if not os.path.exists(output_folder):
        os.mkdir(output_folder)
    # 加载视频
    if os.path.exists(video_path):
        clip = VideoFileClip(video_path)
        print(clip.fps)
    # frames = clip.iter_frames(fps=clip.fps)
    sbList = []  # 分镜数组
    srts = str_parse.read_srt(srt_path)
    timeCur = 0
    for srt in srts:
        print(srt)
        end = srt[2]
        if clip is not None:
            process(sbList, timeCur, srt, clip, clip.fps, output_folder)
        else:
            process_no_clip(sbList, timeCur, srt)
        timeCur = end
    # 关闭视频剪辑对象
    if clip is not None:
        clip.close()
    print("视频转图片完成。")

    return sbList

def process_no_clip(sbList, timeCur, srt):
    text = srt[0]
    start = timeCur
    end = srt[2]
    sbList.append(Storyboard(start, end, text, None, None))


def process(sbList, timeCur, srt, clip, fps, output_folder):
    text = srt[0]
    start = srt[1]
    end = srt[2]
    temp_num = math.ceil((start - timeCur) / perImgDuration)
    if temp_num <= 1111111 :  #1
        index = int(start * fps)
        # 图片命名，这里用帧序号作为名称
        img_name = f"frame-{index}.jpg"
        img_path = f"{output_folder}{img_name}"
        print(img_path)
        if start < clip.duration:
            if not os.path.exists(img_path):
                frame = clip.get_frame(start)
                # 将帧转换为图片并保存
                Image.fromarray(frame).save(img_path)
            print('add', start, end, text, img_name)
            sbList.append(Storyboard(start, end, text, img_name, img_path))
        return

    # for i in range(0, temp_num):
    #     index = int(timeCur * fps + i * fps * perImgDuration)
    #     # 图片命名，这里用帧序号作为名称
    #     img_name = f"frame-{index}.jpg"
    #     img_path = f"{output_folder}{img_name}"
    #     # print(img_path)
    #     if not os.path.exists(img_path):
    #         frame = clip.get_frame(timeCur + i * perImgDuration)
    #         # 将帧转换为图片并保存
    #         Image.fromarray(frame).save(img_path)
    #
    #     innerStart = timeCur + i * perImgDuration
    #     innerEnd = innerStart + perImgDuration
    #     if innerEnd > end:
    #         innerEnd = end
    #     sbList.append(Storyboard(innerStart, innerEnd, text, img_name, img_path))

# split_keyframe()
